package com.example.security.assembly;

import com.example.base.dto.TokenUserDTO;
import com.example.base.utils.JWTUtil;
import com.example.base.utils.RedisUtil;
import com.example.security.filter.JWTAuthenticationFilter;
import com.example.sys.service.ISystemUserService;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    private ISystemUserService service;

    public LoginSuccessHandler(ISystemUserService service){
        this.service = service;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        boolean flag = UserPostLoginAuthenticationToken.class.isAssignableFrom(authentication.getClass());
        //登录成功后写入 token 返回给前端
        if (flag){
            UserPostLoginAuthenticationToken userPostLoginAuthenticationToken = (UserPostLoginAuthenticationToken) authentication;
            TokenUserDTO dto = userPostLoginAuthenticationToken.getUser();
            String token = JWTUtil.generateToken(dto);
            //将token设置到redis中
            RedisUtil.save(JWTAuthenticationFilter.TOKEN_CACHE_PRE + dto.getUserId(), token, JWTAuthenticationFilter.TIME_OUT);
            response.addHeader(HttpHeaders.AUTHORIZATION, token);
        }
    }
}
